package com.dolphin.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.dolphin.commons.ShrioUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 描述:
 * ${DESCRIPTION}
 *
 * @author 小海豚
 * @create 2022-09-14 23:37
 * 个人博客地址：https://www.nonelonely.com
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 新增填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // todo 获取当前登录用户
        Long userId = 1L;
        if (ShrioUtil.getLoginUser() != null) {
            userId = ShrioUtil.getLoginUser().getId();
        }
        fillCreateMeta(metaObject, userId);
        fillUpdateMeta(metaObject, userId);
        fillCommonMeta(metaObject);
    }

    /**
     * 更新填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        // todo 获取当前登录用户
        Long userId = 1L;
        if (ShrioUtil.getLoginUser() != null) {
            userId = ShrioUtil.getLoginUser().getId();
        }
        fillUpdateMeta(metaObject, userId);
        fillCommonMeta(metaObject);
    }

    private void fillCommonMeta(MetaObject metaObject) {
        if (metaObject.hasGetter("version") && metaObject.hasGetter("deleted")) {
            setFieldValByName("version", 1L, metaObject);
            setFieldValByName("deleted", false, metaObject);
        }
    }

    private void fillCreateMeta(MetaObject metaObject, Long userId) {
        if (metaObject.hasGetter("createBy") && metaObject.hasGetter("createTime")) {
            setFieldValByName("createBy", userId, metaObject);
            setFieldValByName("createTime", new Date(), metaObject);
        }
    }

    private void fillUpdateMeta(MetaObject metaObject, Long userId) {
        if (metaObject.hasGetter("updateBy") && metaObject.hasGetter("updateTime")) {
            setFieldValByName("updateBy", userId, metaObject);
            setFieldValByName("updateTime", new Date(), metaObject);
        }
    }
}
